package utils

import (
	"errors"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

func SendSms(phone, code string) error {
	client, err := dysmsapi.NewClientWithAccessKey(ServerConf.Phone.RegionId, ServerConf.Phone.AccessKeyId, ServerConf.Phone.AccessKeySecret)
	if err != nil {
		return errors.New("短信服务异常！")
	}
	request := requests.NewCommonRequest()
	request.Method = ServerConf.Phone.Method
	request.Scheme = ServerConf.Phone.Scheme // https | http
	request.Domain = ServerConf.Phone.Domain
	request.Version = ServerConf.Phone.Version
	request.ApiName = ServerConf.Phone.ApiName
	request.QueryParams["RegionId"] = ServerConf.Phone.RegionId
	request.QueryParams["PhoneNumbers"] = phone                         //手机号
	request.QueryParams["SignName"] = ServerConf.Phone.SignName         //阿里云验证过的项目名 自己设置
	request.QueryParams["TemplateCode"] = ServerConf.Phone.TemplateCode //阿里云的短信模板号 自己设置
	request.QueryParams["TemplateParam"] = "{\"code\":" + code + "}"    //短信模板中的验证码内容 自己生成   之前试过直接返回，但是失败，加上code成功。
	response, err := client.ProcessCommonRequest(request)
	if err != nil {
		fmt.Println(err)
		return errors.New("短信服务器异常！")
	}
	if response.IsSuccess() && response.GetHttpStatus() == 200 {
		return nil
	} else {
		return errors.New("短信发送服务异常！")
	}
}
